package global

import (
	"errors"
	"log"
	"os"

	"github.com/spf13/viper"
)

//FileMapping 配置文件对应的映射
type FileMapping struct {
	MysqlDsn    string `mapstructure:"MYSQL_DSN"`
	PhotoPrefix string `mapstructure:"PHOTO_PREFIX"`
	PhotoPath   string `mapstructure:"PHOTO_PATH"`
	LogFile     string `mapstructure:"LOG_FILE"`
}

var Config FileMapping

// init 加载配置文件
func init() {
	vp := viper.New()
	vp.AddConfigPath("./")
	vp.SetConfigType("yaml")
	vp.SetConfigName("config")
	err := vp.ReadInConfig()
	if err != nil {
		log.Panic(errors.New("read the config file error"))
	}
	err = vp.Unmarshal(&Config)
	if pre := os.Getenv("PHOTO_PREFIX"); pre != "" {
		Config.PhotoPrefix = pre
	}
	if path := os.Getenv("PHOTO_PATH"); path != "" {
		Config.PhotoPath = path
	}
	if logFile := os.Getenv("LOG_FILE"); logFile != "" {
		Config.LogFile = logFile
	}
	if mysqlDsn := os.Getenv("MYSQL_DSN"); mysqlDsn != "" {
		Config.MysqlDsn = mysqlDsn
	}
	if err != nil {
		log.Panic(errors.New("read the config file error"))
	}
}
